package com.yanq.liancar.activity;
/*
 *  @创建者     Administrator
 *  @创建时间   2018/9/26  10:30
 *  @描述       ${TODO}
 */


import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.util.AMapUtils;
import com.yanq.liancar.util.LngLat;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.io.OutputStream;
import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ShopLocationActivity extends BaseToolbarActivity  implements AMap.OnMarkerClickListener{
    @BindView(R.id.img_logo)
    ImageView imgLogo;
    @BindView(R.id.shop_title)
    TextView shopTitle;
    @BindView(R.id.shop_address)
    TextView shopAddress;
    @BindView(R.id.tv_shopaddress)
    TextView tvShopaddress;
    @BindView(R.id.tv_shoppinglun)
    TextView tvShoppinglun;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.ll_shopdetails)
    LinearLayout llShopdetails;
    @BindView(R.id.mapview)
    MapView mapview;

    private AMap mAMap;
    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    private AMapLocationClientOption mLocationOption = null;
    //定义一个UiSettings对象
    private UiSettings mUiSettings;

    private Marker marker;
    private double Latitude, Longitude,sLat,sLong;
    private LatLng markerPosition;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shoplocation);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true,false);
        mTvTitle.setText("店铺地址");
        getLocation();
        RequestOptions options=new RequestOptions();
        options.error(R.mipmap.item_fuwu);
        Glide.with(this).load(getIntent().getStringExtra("logo")).apply(options).into(imgLogo);
        shopTitle.setText(getIntent().getStringExtra("title"));
        shopAddress.setText(getIntent().getStringExtra("address"));
        tvShoppinglun.setText(getIntent().getExtras().getString("pinglun"));
        text.setText(getIntent().getExtras().getString("shoucang"));
        sLat=getIntent().getExtras().getDouble("jing");
        sLong=getIntent().getExtras().getDouble("wei");

        mapview.onCreate(savedInstanceState);
        init();
    }

    /**

     * 初始化AMap对象

     */

    private void init() {

        if (mAMap == null) {

            mAMap=mapview.getMap();

            mUiSettings=mAMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);  //显示缩放按钮
            mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);

            markerPosition= new LatLng(sLat, sLong);
            mAMap.moveCamera(CameraUpdateFactory.changeLatLng(markerPosition));
            mAMap.moveCamera(CameraUpdateFactory.zoomTo(14));

            mAMap.setOnMarkerClickListener(this);

        }

        addGrowMarker();

    }

    /**

     * 添加带生长效果marker

     */

    private void addGrowMarker() {

        MarkerOptions options = new MarkerOptions();

        options.position(markerPosition);

        options.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(),R.drawable.icon_openmap_mark)));

         marker = mAMap.addMarker(options);

        Animation markerAnimation = new ScaleAnimation(0, 1, 0, 1); //初始化生长效果动画

        markerAnimation.setDuration(1000);  //设置动画时间 单位毫秒

        marker.setAnimation(markerAnimation);



    }
    private void getLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationOption = new AMapLocationClientOption();
        //        /**
        //         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
        //         */
        //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //        if(null != mLocationClient){
        //            mLocationClient.setLocationOption(mLocationOption);
        //            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        //            mLocationClient.stopLocation();
        //            mLocationClient.startLocation();
        //        }

        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果
        mLocationOption.setOnceLocation(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        Latitude = aMapLocation.getLatitude();//获取纬度
                        Longitude = aMapLocation.getLongitude();//获取经度
                        LogUtils.e("经纬度====", Latitude + "=======" + Longitude);

                        LngLat end = new LngLat(sLong, sLat);
                        LngLat start = new LngLat(Longitude, Latitude);
                        LogUtils.e("==========",AMapUtils.calculateLineDistance(start, end)+"");
                        if (AMapUtils.calculateLineDistance(start, end)>1000){
                            BigDecimal a = new BigDecimal(AMapUtils.calculateLineDistance(start, end)).divide(new BigDecimal(1000)).setScale(2,BigDecimal.ROUND_DOWN);
                            tvShopaddress.setText(a +"Km");
                        }else {
                            BigDecimal a = new BigDecimal(AMapUtils.calculateLineDistance(start, end)).divide(new BigDecimal(1000)).setScale(0,BigDecimal.ROUND_DOWN);
                            tvShopaddress.setText(a+"m");
                        }


                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError", "location Error, ErrCode:"
                                + aMapLocation.getErrorCode() + ", errInfo:"
                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
        marker.startAnimation();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapview.onSaveInstanceState(outState);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        marker.startAnimation();
        return true;
    }
}
